package com.fang.transfer.file.client.connection;

import com.google.gson.Gson;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.nio.charset.Charset;

public class TcpUtil {

    private String host;
    private int port;
    private Channel channel;

    public TcpUtil(String host, int port) {
        this.host = host;
        this.port = port;
    }


    public void writeAndFlush(String code, Object obj) {
        String jsonData = new Gson().toJson(obj);
        this.writeAndFlush(code, jsonData);
    }

    public void writeAndFlush(String code, String json) {
        channel.writeAndFlush(code + json + "\n");
    }

    public void writeAndFlush(String code) {
        Object o = new Object();
        writeAndFlush(code, o);
    }

    public void connect(final MyChannelInboundHandler inboundHandler) throws InterruptedException {
        final EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new LineBasedFrameDecoder(20480));
                        pipeline.addLast(new StringDecoder(Charset.forName("utf-8")));
                        pipeline.addLast(new StringEncoder(Charset.forName("utf-8")));
                        pipeline.addLast(inboundHandler);
                    }
                });
        //发起异步连接请求，绑定连接端口和host信息
        final ChannelFuture future = b.connect(host, port).await();
        this.channel = future.channel();

    }


    public String getHost() {
        return host;
    }


    public int getPort() {
        return port;
    }

}
